<template>
  <div class="box">
    <el-collapse accordion>
      <el-collapse-item title="修改基本信息">
        <div>
          <el-form
            :model="changeBaseForm"
            ref="changeBaseForm"
            label-width="110px"
            class="demo-dynamic"
          >
            <el-form-item
              prop="stuID"
              label="学生编号"
              :rules="[{ trigger: 'blur' }]"
            >
              <el-input
                v-model="changeBaseForm.recipientId"
                disabled
              ></el-input>
              <!-- @blur="getStuBaseInfo(changeBaseForm.recipientId)" -->
            </el-form-item>
            <el-form-item prop="idNumber" label="收件人身份证号">
              <el-input v-model="changeBaseForm.idNumber" disabled></el-input>
            </el-form-item>
            <el-form-item
              prop="name"
              label="学生姓名"
              :rules="[
                {
                  type: 'string',
                  trigger: 'blur',
                  required: 'true',
                  message: '姓名不能为空'
                }
              ]"
            >
              <el-input v-model="changeBaseForm.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="出生日期">
              <el-col :span="14">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="birthday"
                  style="width: 100%"
                ></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item prop="age" label="年龄">
              <el-input
                type="number"
                v-model="changeBaseForm.age"
                placeholder="不满100周岁"
              ></el-input>
            </el-form-item>
            <el-form-item label="学生所处学段">
              <el-input v-model="showLearingSection" disabled></el-input>
            </el-form-item>
            <el-form-item label="修改学生学段">
              <el-cascader
                v-model="learningSection"
                :options="options"
                :props="{ expandTrigger: 'hover' }"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="学校">
              <el-input v-model="changeBaseForm.school"></el-input>
            </el-form-item>
            <el-form-item label="政治面貌">
              <el-select
                v-model="changeBaseForm.politicalOutlook"
                placeholder="请选择政治面貌"
              >
                <el-option label="中共党员" value="中共党员"></el-option>
                <el-option
                  label="中共预备党员"
                  value="中共预备党员"
                ></el-option>
                <el-option label="少先队员" value="少先队员"></el-option>
                <el-option label="共青团员" value="共青团员"></el-option>
                <el-option label="民革会员" value="民革会员"></el-option>
                <el-option label="民盟盟员" value="民盟盟员"></el-option>
                <el-option label="民建会员" value="民建会员"></el-option>
                <el-option label="民进会员" value="民进会员"></el-option>
                <el-option label="农工党党员" value="农工党党员"></el-option>
                <el-option label="致公党党员" value="致公党党员"></el-option>
                <el-option
                  label="九三学社社员"
                  value="九三学社社员"
                ></el-option>
                <el-option label="台盟盟员" value="台盟盟员"></el-option>
                <el-option label="无党派人士" value="无党派人士"></el-option>
                <el-option
                  label="群众(普通居民)"
                  value="群众(普通居民)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="收款账户"
              prop="accountNumber"
              :rules="[
                {
                  type: 'string',
                  trigger: 'blur',
                  required: 'true',
                  pattern: /^\S||([1-9]{1})(\d{14}|\d{18})$/,
                  message: '请输入正确的银行卡号码'
                }
              ]"
            >
              <el-input
                v-model="changeBaseForm.accountNumber"
                placeholder="15-19位卡号"
              ></el-input>
            </el-form-item>
            <el-form-item label="收货地址">
              <el-input
                v-model="changeBaseForm.receivingAddress"
                placeholder="仅限云南地区"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="目标金额"
              prop="targetMoney"
              :rules="[
                {
                  type: 'number',
                  required: true,
                  message: '金额输入有误',
                  min: 0,
                  max: 1000000
                }
              ]"
            >
              <el-input
                type="number"
                v-model.number="changeBaseForm.targetMoney"
                placeholder="数值"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitChangeForm"
                >确认修改</el-button
              >
              <el-button @click="resetForm('changeBaseForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 修改学习情况 -->
      <el-collapse-item title="修改学习情况">
        <div>
          <el-form
            :model="changeLearnForm"
            ref="changeLearnForm"
            label-width="100px"
            class="demo-dynamic"
          >
            <el-form-item label="成绩编号">
              <el-input
                v-model="changeLearnForm.lsid"
                @blur="getStudyInfoByLsid(changeLearnForm.lsid)"
              ></el-input>
            </el-form-item>
            <el-form-item
              prop="examName"
              label="考试名称"
              :rules="[
                {
                  required: true,
                  message: '考试名称不能为空',
                  pattern: /\S/,
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                v-model="changeLearnForm.examinationName"
                placeholder="例：第一次模拟考"
              ></el-input>
            </el-form-item>
            <el-form-item label="学生编号">
              <el-input
                v-model="changeLearnForm.recipientId"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item
              prop="classRanking"
              label="班级排名"
              :rules="[
                {
                  required: true,
                  message: '排名不能为空',
                  pattern: /\S/,
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                type="Number"
                v-model="changeLearnForm.classRanking"
              ></el-input>
            </el-form-item>
            <el-button
              type="warning"
              plain
              style="margin-left: 30px; margin-bottom: 10px"
              @click="addDomain"
              round
              >新增单科成绩</el-button
            >
            <el-form-item v-for="domain in domains" :key="domain.index">
              <el-input
                v-model="domain.subject"
                placeholder="请输入科目"
                class="input-with-subject"
              ></el-input>
              <el-input
                v-model="domain.value"
                placeholder="请输入分数"
                class="input-with-fraction"
              ></el-input>
              <el-button
                circle
                @click.prevent="removeDomain(domain)"
                icon="el-icon-delete"
                v-if="domains.length !== 1"
              ></el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="upLearnForm" :disabled="isLearn"
                >确认修改</el-button
              >
              <el-button @click="resetForm('changeLearnForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-item>

      <!-- 修改获奖情况 -->
      <el-collapse-item title="修改获奖情况">
        <div>
          <el-form
            :model="changeAwdForm"
            ref="changeAwdForm"
            label-width="100px"
            class="demo-dynamic"
          >
            <el-form-item label="获奖编号">
              <el-input
                v-model="changeAwdForm.awardId"
                @blur="getStuAward(changeAwdForm.awardId)"
              ></el-input>
            </el-form-item>
            <el-form-item
              prop="awardName"
              label="获奖名称"
              :rules="[
                {
                  required: true,
                  message: '请输入证书名称',
                  pattern: /\S/,
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                v-model="changeAwdForm.awardName"
                placeholder="证书名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="获奖人编号">
              <el-input
                v-model="changeAwdForm.recipientId"
                placeholder="获奖人编号"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="获奖时间">
              <el-col :span="14">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="awardTime"
                  style="width: 100%"
                ></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="证书图片">
              <div style="width: 200px">
                <img width="100%" :src="imgSrc" />
              </div>
            </el-form-item>
            <el-form-item>
              <input type="button" id="btn" value="点击上传获奖证书" />
              <input
                id="img"
                style="opacity: 0"
                type="file"
                @change="showImg($event, 'changeAwdForm')"
                ref="file"
                name="file"
              />
              <div>{{ fileName }}</div>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitAwdForm"
                :disabled="isAwad"
                >确认修改</el-button
              >
              <el-button @click="resetForm('changeAwdForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-item>
      <el-collapse-item title="其他信息">
        <div class="add">
          <el-form
            :model="changeOthForm"
            ref="changeOthForm"
            label-width="100px"
            class="demo-dynamic"
          >
            <el-form-item label="其他情况编号">
              <el-input
                v-model="changeOthForm.othersId"
                @blur="getStuOtherInfo(changeOthForm.othersId)"
              ></el-input>
            </el-form-item>
            <el-form-item label="获奖人编号">
              <el-input
                v-model="changeOthForm.recipientId"
                placeholder="获奖人编号"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="文本">
              <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 10 }"
                placeholder="请输入内容"
                v-model="changeOthForm.othersText"
                style="width:500px"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="图片">
              <div style="width: 200px">
                <img width="100%" :src="otherImg" />
              </div>
            </el-form-item>
            <el-form-item>
              <input type="button" id="btn" value="点击上传图片" />
              <input
                id="img"
                style="opacity: 0"
                type="file"
                ref="otherFile"
                name="otherFile"
                @change="showImg($event, 'changeOthForm')"
              />
              <div>{{ otherName }}</div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="upOtherForm" :disabled="isOther"
                >确认修改</el-button
              >
              <el-button @click="resetForm('changeOthForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script>
import {
  updateBaseInfo,
  updateLearn,
  updateAward,
  updateOther,
  getStuBaseInfoById,
  getStuAwardByAid,
  getStuOtherInfoById,
  getStudyInfoByLsId
} from "network/charity.js";

// 引入公共数据中的数据
import { options } from "common/commonData";
import { formatDate } from "common/utils";
export default {
  name: "ChangeStuMsg",
  props: {},
  data() {
    return {
      isOther: false,
      isAwad: false,
      isLearn: false,
      awardTime: "",
      birthday: "",
      learningSection: [],
      showLearingSection: "",
      fileName: "",
      imgSrc: "",
      otherImg: "",
      otherName: "",
      rules: "",
      studyMap: {
        数学: 99,
        语文: 80,
        化学: 79,
        英语: 89
      },
      domains: [
        {
          subject: "",
          value: ""
        }
      ],
      changeBaseForm: {
        recipientId: "1699325984",
        idNumber: "",
        name: "",
        birthday: "",
        age: "",
        learningSection: "",
        school: "",
        accountNumber: "",
        receivingAddress: "",
        targetMoney: "",
        politicalOutlook: ""
      },
      changeLearnForm: {
        lsid: "1",
        examinationName: "",
        scores: "",
        classRanking: ""
      },
      changeAwdForm: {
        awardId: 1,
        awardName: "",
        awardTime: "",
        file: "",
        recipientId: ""
      },
      changeOthForm: {
        othersId: 1,
        othersText: "",
        file: "",
        recipientId: ""
      },
      options: options
    };
  },
  methods: {
    /**
     * @function 指定考试编号得到学生学习信息
     */
    getStudyInfoByLsid(lsId) {
      getStudyInfoByLsId(lsId)
        .then(res => {
          if (res.learningstatusInformationDonation) {
            let studyMap = res.learningstatusInformationDonation;
            this.changeLearnForm = studyMap;
            let examMap = studyMap.examinationResultsMap;
            if (studyMap.recipientId == this.changeBaseForm.recipientId) {
              this.isLearn = false;
            } else {
              this.isLearn = true;
            }
            this.domains.splice(0);
            for (let item in examMap) {
              this.domains.unshift({
                subject: item,
                value: examMap[item]
              });
            }
          } else {
            this.$message({
              showClose: true,
              message: "检查成绩编号是否正确！",
              type: "warning"
            });
          }
        })
        .catch(err => {
          // alert(err);
        });
    },
    /**
     * @function 指定学习情况id更新学习情况信息
     */
    upLearnForm() {
      let academic = this.domains;
      let str = "";
      // 拼接成绩字符串
      academic.forEach(element => {
        str += element.subject + ":" + element.value + ",";
      });
      // 删除不必要传输的项
      this.changeLearnForm.examinationResults = str;
      // console.log(str);
      for (let x in this.changeLearnForm) {
        delete this.changeLearnForm["examinationResultsMap"];
      }
      // 截取字符串
      let site = str.lastIndexOf(",");
      this.changeLearnForm["examinationResults"] = str.substring(0, site);

      updateLearn(this.changeLearnForm)
        .then(res => {
          if (res.msg == "success") {
            this.$message({
              showClose: true,
              message: `成绩编号${this.changeLearnForm.lsid}修改成功 `,
              type: "success"
            });
          } else {
            this.$message({
              showClose: true,
              message: `成绩编号${this.changeLearnForm.lsid}修改失败！`,
              type: "error"
            });
          }
        })
        .catch(err => {
          console.error(err);
        });
    },
    /**
     * @author DJG
     * @function 查询指定id学生基本信息
     */
    getStuBaseInfo(stuID) {
      getStuBaseInfoById(stuID).then(res => {
        if (res.basicInformationDonation) {
          this.changeBaseForm = res.basicInformationDonation;
          this.showLearingSection =
            res.basicInformationDonation["learningSection"];
          this.birthday = res.basicInformationDonation["birthday"];
        } else {
        }
      });
    },
    /**
     * @author  DJG
     * 提交修改学生基本信息表单
     */
    submitChangeForm() {
      // 删除表单中的创建时间
      for (let x in this.changeBaseForm) {
        delete this.changeBaseForm["createTime"];
        delete this.changeBaseForm["status"];
        delete this.changeBaseForm["text"];
        if (!this.changeBaseForm[x]) {
          this.$message({
          showClose: true,
          message: "数据不能为空！",
          type: "warning"
        });
          return;
        }
      }
      updateBaseInfo(this.changeBaseForm).then(res => {
        if (res.msg == "success") {
          this.$message({
          showClose: true,
          message: `${this.changeBaseForm["name"]}的基本信息修改成功！`,
          type: "success"
        });
        } else {
          this.$message({
          showClose: true,
          message: `${this.changeBaseForm["name"]}的基本信息修改失败！`,
          type: "error"
        });
        }
      });
    },
    /**
     * @author
     * @function 回显图片以及为file赋值
     */
    showImg(e, formName) {
      // 显示图片
      let file = e.target.files[0];
      if (formName == "changeAwdForm") {
        this.imgSrc = window.URL.createObjectURL(file);
        this.fileName = file.name;
        // console.log(this.fileName);
        this.changeAwdForm.file = file;
      } else if (formName == "changeOthForm") {
        this.otherImg = window.URL.createObjectURL(file);
        this.otherName = file.name;
        this.changeOthForm.file = file;
      }
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    removeDomain(item) {
      var index = this.domains.indexOf(item);
      if (index !== 0) {
        this.domains.splice(index, 1);
      }
    },
    addDomain() {
      this.domains.push({
        key: Date.now(),
        value: ""
      });
    },
    /**
     * @function 指定荣誉Id得到学生荣誉
     */
    getStuAward(awardId) {
      getStuAwardByAid(awardId).then(res => {
        if (res.awardInformationDonation) {
          this.changeAwdForm = res.awardInformationDonation;
          this.awardTime = res.awardInformationDonation["awardTime"];
          if (
            this.changeBaseForm.recipientId ==
            res.awardInformationDonation["recipientId"]
          ) {
            this.isAwad = false;
          } else {
            this.isAwad = true;
          }
          this.fileName = this.imgSrc =
            res.awardInformationDonation["awardImg"];
        } else {
          this.$message({
          showClose: true,
          message: "检查学生荣誉编号是否输入正确！",
          type: "warning"
        });
        }
      });
    },
    /**
     * @author  DJG
     * 提交修改学生荣誉信息表单
     */
    submitAwdForm() {
      let form = this.changeAwdForm;
      // console.log(form);
      let formData = new FormData();
      formData.append("awardId", form.awardId);
      formData.append("awardTime", form.awardTime);
      if (form.file === undefined) {
        formData.append("file", new Blob(), "/path/to/file");
      } else {
        formData.append("file", form.file);
      }

      formData.append("awardName", form.awardName);
      updateAward(formData).then(res => {
        if (res.msg == "success") {
          this.$message({
          showClose: true,
          message: `荣誉${form.awardId}修改成功！`,
          type: "warning"
        });
        }
      });
    },
    /**
     * @function 指定其他信息Id得到学生其他信息
     */
    getStuOtherInfo(othersId) {
      getStuOtherInfoById(othersId).then(res => {
        if (res.othersInformationDonation) {
          this.otherName = this.otherImg =
            res.othersInformationDonation["othersImg"];
          this.changeOthForm = res.othersInformationDonation;
          if (
            this.changeOthForm.recipientId == this.changeBaseForm.recipientId
          ) {
            this.isOther = false;
          } else {
            this.isOther = true;
          }
        } else {
          this.$message({
          showClose: true,
          message: "请检查其他信息编号是否输入正确！",
          type: "warning"
        });
        }
      });
    },
    /**
     * @author  DJG
     * 提交修改学生其他信息表单
     */
    upOtherForm() {
      let form = this.changeOthForm;
      // console.log(form);
      let formData = new FormData();
      formData.append("othersId", form.othersId);
      formData.append("othersText", form.othersText);
      // 判断是否修改图片信息
      if (form.file === undefined) {
        formData.append("file", new Blob(), "/path/to/file");
      } else {
        formData.append("file", form.file);
      }
      updateOther(formData).then(res => {
        if (res.msg == "success") {
          this.$message({
          showClose: true,
          message:`其他信息编号${form.othersId}修改成功！`,
          type: "success"
        });
        } else {
          this.$message({
          showClose: true,
          message: "检查信息是否输入正确！",
          type: "warning"
        });
        }
      });
    },
    /**
     * @function 从路由获取学生ID
     */
    isGetRidtoUrl() {
      let _this = this;
      _this.changeBaseForm.recipientId = this.$route.query.id;
      _this.getStuBaseInfo(_this.changeBaseForm.recipientId);
    }
  },
  components: {},

  computed: {},

  beforeMount() {},

  mounted() {},

  watch: {
    // 监听学段数据变化并且更新到form对象中
    learningSection() {
      let str = this.learningSection.join("");
      if (str) {
        this.changeBaseForm.learningSection = this.showLearingSection = str;
      }
    },
    //将时间处理成后端接受的格式
    birthday() {
      let d = this.birthday;
      try {
        this.changeBaseForm.birthday = formatDate(d, "yyyy-MM-dd");
      } catch (error) {}
    },
    awardTime() {
      try {
        this.changeAwdForm.awardTime = formatDate(this.awardTime, "yyyy-MM-dd");
      } catch (error) {}
    }
  },
  created() {
    this.isGetRidtoUrl();
  }
};
</script>
<style scoped lang="scss">
.box {
  width: 80%;
  margin-top: 20px;
  padding: 20px;
  margin-left: 80px;
  // border: 2px solid rgb(241, 163, 111);
  background-color: rgb(240, 212, 186);
  box-shadow: 0px 0px 5px rgb(241, 163, 111);
}
// .el-form-item {
//   display: inline-block;
//   width: 50%;
// }
.el-input {
  width: 60%;
}
.demo-dynamic {
  text-align: left;
}
#img {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
}

.el-form-item__content {
  margin-left: 10px;
}

.input-with-fraction {
  width: 100px;
  margin-bottom: 10px;
  margin-right: 10px;
}
.input-with-subject {
  width: 100px;
  margin-bottom: 10px;
  margin-right: 10px;
}
</style>
